"""
主应用类
负责PySide6应用生命周期管理
"""

import sys
import platform
from pathlib import Path

try:
    import tomllib  # Python 3.11+
except ImportError:
    import tomli as tomllib  # Python 3.10及以下

from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QTranslator, QLocale
from PySide6.QtGui import QIcon

from ..ui.main_window import MainWindow
from ..config.settings import AppConfig


class ColorBlockDownloaderApp:
    """色块下载器主应用类"""
    
    def __init__(self):
        """初始化应用"""
        self.app = QApplication(sys.argv)
        self.main_window = None
        self._setup_application()
    
    def _get_project_info(self):
        """从pyproject.toml获取项目信息"""
        project_root = Path(__file__).parent.parent.parent
        pyproject_path = project_root / "pyproject.toml"
        
        with open(pyproject_path, 'rb') as f:
            config = tomllib.load(f)
            
        project = config['project']
        return {
            'name': project['description'] or project['name'],
            'version': project['version']
        }
    
    def _setup_application(self):
        """设置应用基本属性"""
        # 从配置文件读取项目信息
        project_info = self._get_project_info()
        
        # 设置应用信息
        self.app.setApplicationName(project_info['name'])
        self.app.setApplicationVersion(project_info['version'])
        self.app.setApplicationDisplayName(project_info['name'])
        
        # 设置应用图标（根据操作系统选择对应格式）
        icons_dir = Path(__file__).parent.parent.parent / "resources" / "icons"
        
        system = platform.system().lower()
        if system == "windows":
            icon_file = "app-icon.ico"
        elif system == "darwin":  # macOS
            icon_file = "app-icon.icns"
        else:  # Linux和其他系统
            icon_file = "app-icon.png"
        
        icon_path = icons_dir / icon_file
        if icon_path.exists():
            self.app.setWindowIcon(QIcon(str(icon_path)))
    
    def _setup_translator(self):
        """设置翻译器（如果需要国际化）"""
        translator = QTranslator()
        locale = QLocale.system().name()
        
        # 这里可以加载翻译文件
        # translator.load(f":/translations/{locale}.qm")
        # self.app.installTranslator(translator)
    
    def run(self) -> int:
        """
        运行应用
        
        Returns:
            int: 应用退出码
        """
        try:
            # 创建主窗口
            self.main_window = MainWindow()
            self.main_window.show()
            
            # 运行应用事件循环
            return self.app.exec()
            
        except Exception as e:
            print(f"应用运行错误: {e}")
            return 1
    
    def quit(self):
        """退出应用"""
        if self.main_window:
            self.main_window.close()
        self.app.quit()